﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

namespace BeerManagementSystem
{
    public partial class GameCamel : System.Windows.Controls.UserControl
    {
        private LogWriter log;
        private User cardOwner;
        ReadCard readCard;
        private string userImagePath = AppDomain.CurrentDomain.BaseDirectory + "UserImages\\";
        private string programmPath = AppDomain.CurrentDomain.BaseDirectory ;
        private System.Drawing.Size userImageSize = new System.Drawing.Size(80, 80);
        private System.Drawing.Size userButtonSize = new System.Drawing.Size(70, 30);
        public EventHandler crossedFinishLine;

        
        LinqToBeerDataContext data;


        public GameCamel()
        {
            data = new LinqToBeerDataContext();
            InitializeComponent();
            updateGame();
            crossedFinishLine += new EventHandler(_playerWon);
            
        }

        private void _playerWon(object o, EventArgs e)
        {
            System.Windows.Forms.MessageBox.Show("Gewonnen");

        }

        public bool isPlaying(Transaction t)
        {
            
            var checkPlayer =
                from p in data.Game_Camel
                where p.UserID == t.UserID
                select p;
           
            if (checkPlayer.Any()) return true;
            return false;
        }
        public bool isPlaying(User u)
        {
            var checkPlayer =
                from p in data.Game_Camel
                where p.UserID == u.ID
                select p;
            
            if (checkPlayer.Any()) return true;
            return false;
        }
        public void setUserPos(Transaction t)
        {
            var PlayeronGame =
                from p in data.Game_Camel
                where p.UserID == t.UserID
                select p;

            camelMainCanvas.Children.Clear();                       

            if (isPlaying(t))
            {
                PlayeronGame.First().PosX += stepForward();
                data.SubmitChanges();
                
            }
            updateGame();
        }

        private int getRandomInt()
        {
            Random random = new Random();
            int randomInt = random.Next(1, 3);
            return randomInt;
        }

        private void updateGame()
        {
            listBox1.Items.Clear();            
            updatePlayer();
            updateCamels();

        }
        private void updatePlayer()
        {
            userCanvas.Children.Clear();
            foreach (Game_Camel Player in data.Game_Camel)
            {                
                try
                {
                    Canvas childCanvas = new Canvas();
                    childCanvas.BeginInit();
                    Canvas.SetTop(childCanvas, Convert.ToInt32(Player.PosY));
                    Canvas.SetLeft(childCanvas, 0.0);
                    System.Windows.Controls.Image image = new System.Windows.Controls.Image
                    {
                        Width = 80,
                        Height = 100,
                        Source = new BitmapImage(new Uri(userImagePath + Player.User.FirstName + "_" + Player.User.LastName + ".jpg", UriKind.Absolute))
                    
                    };
                    image.RenderSize = new System.Windows.Size(80, 100);
                    childCanvas.Children.Add(image);
                    childCanvas.EndInit();
                    userCanvas.Children.Add(childCanvas);

                }
                catch (Exception ex) 
                { //log.WriteMessage(ex.StackTrace); 
                }


            }
        }
        private void updateCamels()
        {
            camelMainCanvas.Children.Clear();
            foreach (Game_Camel Player in data.Game_Camel)
            {
                listBox1.Items.Add(Player.User.FirstName + " " + " X : " + Player.PosX + "Y : " + Player.PosY);
                //log.WriteMessage(Player.User.FirstName + " " + " X : " + Player.PosX + "Y : " + Player.PosY);

                try
                {
                    Canvas childCanvas = new Canvas();
                    childCanvas.BeginInit();
                    //bestimmt die Position des Camels
                    Canvas.SetTop(childCanvas, Convert.ToInt32(Player.PosY));
                    if (Player.PosX < camelMainCanvas.Width) Canvas.SetLeft(childCanvas, Convert.ToInt32(Player.PosX));
                    else
                    {
                        Canvas.SetLeft(childCanvas, camelMainCanvas.Width);
                        crossedFinishLine(null, null);
                    }
                    System.Windows.Controls.Image image = new System.Windows.Controls.Image
                    {
                        Width = 80,
                        Height = 100,
                        Source = new BitmapImage(new Uri(userImagePath + "camel.png", UriKind.Absolute))
                    };
                    image.RenderSize = new System.Windows.Size(80, 100);
                    childCanvas.Children.Add(image);
                    childCanvas.EndInit();
                    camelMainCanvas.Children.Add(childCanvas);

                }
                catch (Exception ex) { //log.WriteMessage(ex.StackTrace); 
                }


            }
        }
        private BitmapImage createUserImage(User user)
        {


            try
            {
                BitmapImage bild = new BitmapImage();
                bild.BeginInit();
                bild.UriSource = new Uri(userImagePath + user.FirstName + "_" + user.LastName + ".jpg", UriKind.Absolute);
                bild.EndInit();

                return bild;

            }
            catch (Exception ex)
            {
                //log.WriteMessage(ex.StackTrace);
                try
                {
                    BitmapImage bild = new BitmapImage();
                    bild.BeginInit();
                    bild.UriSource = new Uri(userImagePath + "Default.ico", UriKind.Absolute);
                    bild.EndInit();
                    return bild;

                }
                catch (Exception ex2)
                {
                    //log.WriteMessage(ex2.StackTrace);
                    return null;
                }
            }

        }

        // neuen Spieler hinzufuegen
        private void addPlayer(User user)
        {           

            var GameCamelPlayers =
                from p in data.Game_Camel
                orderby p.PosY descending
                select p;
            Game_Camel Player = new Game_Camel();

            try
            {     
                Player.UserID = user.ID;                
                Player.PosX = 0;
                Player.PosY = 0;


                if (GameCamelPlayers.Count() > 0)
                {
                    Player.PosY = GameCamelPlayers.First().PosY + 100;
                }
                else { Player.PosY = 0; }

                data.Game_Camel.InsertOnSubmit(Player);
                if (!isPlaying(user))
                {
                    data.SubmitChanges();
                }
                else System.Windows.MessageBox.Show("User spielt bereits");
            }
            catch (Exception ex)
            {
                //log.WriteMessage(ex.StackTrace);
                System.Windows.MessageBox.Show("User spielt gerade oder ist nicht vorhanden");
                
            }
            finally 
            { 
                updateGame();
                userControlCanvas.Children.Clear();
                
            }


        }        

        private void GameCamel_Load(object sender, EventArgs e)
        {

        }

        private void newGameButton_Click(object sender, RoutedEventArgs e)
        {
            data.Game_Camel.DeleteAllOnSubmit(data.Game_Camel);
            data.SubmitChanges();        

            updateGame();
        }

        private void deletePlayerButton_Click(object sender, EventArgs e)
        {
            deleteLastPlayer();
            updateGame();   
        }

        private void deleteLastPlayer()
        {
            var GameCamelPlayers =
                    from p in data.Game_Camel
                    orderby p.PosY descending
                    select p;
            if (data.Game_Camel.Any())
            {
                data.Game_Camel.DeleteOnSubmit(GameCamelPlayers.First());
                data.SubmitChanges();
                updateGame();
            }
        }

        private void updateButton_Click(object sender, RoutedEventArgs e)
        {
            updateGame();
        }

        private void ReadCard_Click(object sender, RoutedEventArgs e)
        {
            readCard = new ReadCard(log);
            userControlCanvas.Children.Add(readCard);
            readCard.cardRead += new EventHandler(_newPlayerCardRead);            
        }

        private void _newPlayerCardRead(object o, EventArgs e)
        {            
            addPlayer(readCard.getCardOwner());
        }

        private User getPlayer(Transaction t)
        {
            var GameCamelPlayers =
                from p in data.Game_Camel
                where p.UserID == t.UserID
                select p;
            return GameCamelPlayers.First().User;
        }
        private int stepForward()
        {
            double d = camelMainCanvas.Width / 3 / Convert.ToInt32(gameAimLabel.Text) * getRandomInt();
            return Convert.ToInt32(d);
        }

    

       
    }
}